package com.gitee.ed.structure.map;

import cn.hutool.core.lang.Pair;

import java.util.HashMap;

/**
 * 复合两个值作为唯一键的 HashMap 结构
 *
 * @author hongda.li
 */
public class DoubleKeyMap<K1, K2, V> extends HashMap<Pair<K1, K2>, V> {

    public DoubleKeyMap() {
        this(8);
    }

    public DoubleKeyMap(int initialCapacity) {
        super((int) (initialCapacity / 0.75F) + 1);
    }

    public DoubleKeyMap(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor);
    }

    public DoubleKeyMap(DoubleKeyMap<K1, K2, V> otherMap) {
        super(otherMap);
    }

    public V get(K1 k1, K2 k2) {
        return this.get(new Pair<>(k1, k2));
    }

    public Object put(K1 k1, K2 k2, V value) {
        this.put(new Pair<>(k1, k2), value);
        return value;
    }

    public V putIfAbsent(K1 k1, K2 k2, V value) {
        return this.putIfAbsent(new Pair<>(k1, k2), value);
    }

    public boolean containsKey(K1 k1, K2 k2) {
        return this.containsKey(new Pair<>(k1, k2));
    }

    public void foreach(Consumer<K1, K2, V> consumer) {
        this.forEach((pair, value) -> consumer.accept(pair.getKey(), pair.getValue(), value));
    }

    public V removeIt(K1 k1, K2 k2) {
        return this.remove(new Pair<>(k1, k2));
    }

    public V replaceIt(K1 k1, K2 k2, V value) {
        return this.replace(new Pair<>(k1, k2), value);
    }

    public boolean replaceIt(K1 k1, K2 k2, V oldValue, V newValue) {
        return this.replace(new Pair<>(k1, k2), oldValue, newValue);
    }

    @FunctionalInterface
    public interface Consumer<K1, K2, V> {
        /**
         * 接收参数并执行处理逻辑
         *
         * @param k1 第一个键
         * @param k2 第二个键
         * @param v  键对应的值
         */
        void accept(K1 k1, K2 k2, V v);
    }
}
